package com.emm.yixun.website.controller.system;

//框架包
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.emm.yixun.common.model.BaseCodeType;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.BaseCodeValueInfo;
import com.emm.yixun.common.model.Customer;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeTypeDto;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.CustomerDto;
import com.emm.yixun.common.model.dto.ProjectDto;
import com.emm.yixun.common.model.enums.BaseCodeTypeEnum;
import com.emm.yixun.common.model.enums.BuyCarEnum;
import com.emm.yixun.common.model.enums.CodeTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.IsOwnerCompanyEnum;
import com.emm.yixun.common.model.enums.PaymentMethodEnum;
import com.emm.yixun.common.model.enums.XuQiuHuXingEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.EnumUtil;
import com.emm.yixun.customer.service.CustomerServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.system.service.BaseCodeTypeServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.UserServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.constant.EhcacheConstant;
import com.emm.yixun.website.controller.base.BaseController;
//common
//website
//变化的引用
import com.emm.yixun.website.service.CacheUtils;

@Controller
@RequestMapping("/system/baseCodeValue/")
public class BaseCodeValueController extends BaseController<BaseCodeValue> {

	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade;
	@Autowired
	private BaseCodeTypeServiceFacade baseCodeTypeServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private UserServiceFacade userServiceFacade;
	@Autowired
	private CustomerServiceFacade customerServiceFacade;
	@Autowired
	public CacheUtils cacheUtils;

	/**
	 * 业务参数详情
	 * @param projectId
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "baseCodeValueList")
	public String BaseCodeValueList(String projectId, ModelMap map) {
		//if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			map.put("projectId", projectId);
			return "/system/basecode/basecodevalue/list";
		//}
		//return Const.NO_AUTHORIZED_URL;
	}
	
	/**
	 * 项目列表
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/system/basecode/basecodevalue/project_list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(BaseCodeValueDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "system:baseCodeValue:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				// 判断是否存在同名参数
				BaseCodeValueDto bcvDto = new BaseCodeValueDto();
				bcvDto.setCodeName(dto.getCodeName());
				bcvDto.setTypeId(dto.getTypeId());
				bcvDto.setProjectId(dto.getProjectId());
				bcvDto.setMerchantId(user.getMerchantId());
				ResponseList<BaseCodeValue> resListBcv = baseCodeValueServiceFacade.findByDto(bcvDto);
				if (null != resListBcv && null != resListBcv.getEntity() && resListBcv.getEntity().size() > 0) {
					ar.setFailMsg("该参数[" + dto.getCodeName() + "]已存在,请勿重复添加!");
					return ar;
				} else {
					//当codeValue为空时，设置为codeName
					if(StringUtils.isBlank(bcvDto.getCodeValue())){
						bcvDto.setCodeValue(dto.getCodeName());
					}
					dto.setMerchantId(user.getMerchantId());
					dto.setCreateUserId(user.getId());
					dto.setDelFlag("0");
					dto.setUpdateUserId(user.getId());
					dto.setUpdateTime(new Date());
					Response<BaseCodeValueDto> response = baseCodeValueServiceFacade.save(dto);
					if (response.isSuccess()) {
						ar.setSucceedMsg(Const.SAVE_SUCCEED);
					} else {
						ar.setFailMsg(Const.SAVE_FAIL);
					}
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "system:baseCodeValue:view"))) {
			try {
				Response<BaseCodeValue> response = baseCodeValueServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(BaseCodeValueDto dto) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "system:baseCodeValue:edit"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				// 判断是否存在同名参数
				BaseCodeValueDto bcvDto = new BaseCodeValueDto();
				bcvDto.setCodeName(dto.getCodeName());
				//bcvDto.setCodeValue(dto.getCodeValue());
				bcvDto.setTypeId(dto.getTypeId());
				bcvDto.setProjectId(dto.getProjectId());
				bcvDto.setMerchantId(user.getMerchantId());
				bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				ResponseList<BaseCodeValue> resListBcv = baseCodeValueServiceFacade.findByDto(bcvDto);
				if (null != resListBcv && null != resListBcv.getEntity()) {
					if (resListBcv.getEntity().size() == 1) {
						if (!resListBcv.getEntity().get(0).getId().equals(dto.getId())) {
							ar.setFailMsg("该参数已存在,请勿重复添加!");
							return ar;
						} else {
							dto.setUpdateUserId(user.getId());
							dto.setCodeValue(dto.getCodeName());
							Response<Integer> response = baseCodeValueServiceFacade.updateByPrimaryKey(dto, true);
							if (response.isSuccess()) {
								ar.setSucceedMsg(Const.UPDATE_SUCCEED);
							} else {
								ar.setFailMsg(Const.UPDATE_FAIL);
							}
						}
					} else {
						ar.setFailMsg("该参数已存在,请勿重复添加!");
						return ar;
					}
				} else {
					dto.setUpdateUserId(user.getId());
					Response<Integer> response = baseCodeValueServiceFacade.updateByPrimaryKey(dto, true);
					if (response.isSuccess()) {
						ar.setSucceedMsg(Const.UPDATE_SUCCEED);
					} else {
						ar.setFailMsg(Const.UPDATE_FAIL);
					}
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "system:baseCodeValue:delete"))) {
			try {
				Response<Integer> response = baseCodeValueServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes list(BaseCodeValueDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "system:baseCodeValue:list"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setOrders("t.sort*1");
				Page<BaseCodeValue> response = baseCodeValueServiceFacade.findPageByDto(dto,
						PageUtil.begin(pageNum, pageSize), pageSize);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<BaseCodeValue>());
					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	@RequestMapping(value = "getCodeValueByType")
	@ResponseBody
	public List<BaseCodeValueDto> getCodeValueByType(String typeId, String delFlag) {
		User user = ShiroUtil.getCurrentUser();
		String typeName = BaseCodeTypeEnum.getByNo(typeId).getDes();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeName);
		if (StringUtils.isNotBlank(delFlag)) {
			bcvDto.setDelFlag(delFlag);
		} else {
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		}
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		ResponseList<BaseCodeValueDto> resList = baseCodeValueServiceFacade.findListByTypeName(bcvDto);
		List<BaseCodeValueDto> bctList = new ArrayList<BaseCodeValueDto>();
		if (null != resList && resList.getEntity() != null && resList.getEntity().size() > 0) {
			bctList = resList.getEntity();
		}
		return bctList;
	}
	
	@RequestMapping(value = "getCodeNameByType")
	@ResponseBody
	public List<BaseCodeValueDto> getCodeNameByType(String projectId, String typeValue, String delFlag) {
		List<BaseCodeValueDto> bctList = new ArrayList<BaseCodeValueDto>();
		if(StringUtils.isBlank(projectId)){
			return bctList;
		}
		
		User user = ShiroUtil.getCurrentUser();
		BaseCodeValueDto bcvDto = new BaseCodeValueDto();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeValue(typeValue);
		bcvDto.setProjectId(Long.parseLong(projectId));
		if (StringUtils.isNotBlank(delFlag)) {
			bcvDto.setDelFlag(delFlag);
		} else {
			bcvDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		}
		// *1解决数字排序问题.例如 1,2,10.排序后会显示成 1,10,2
		bcvDto.setOrders("t.sort*1");
		ResponseList<BaseCodeValueDto> resList = baseCodeValueServiceFacade.findListByTypeName(bcvDto);
		if (null != resList && resList.getEntity() != null && resList.getEntity().size() > 0) {
			bctList = resList.getEntity();
		}
		return bctList;
	}

	// 新增返回实体对象
	@RequestMapping(value = "init")
	@ResponseBody
	public AjaxRes init(BaseCodeValueDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		// if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:baseCodeValue:init"))){
		try {
			if(dto.getProjectId() == null){
				ar.setFailMsg("请设置projectId");
				return ar;
			}
			User user = ShiroUtil.getCurrentUser();
			BaseCodeTypeDto bctDto = new BaseCodeTypeDto();
			bctDto.setRemark("初始化");
			bctDto.setMerchantId(user.getMerchantId());
			bctDto.setProjectId(dto.getProjectId());
			ResponseList<BaseCodeType> bctRes = baseCodeTypeServiceFacade.findByDto(bctDto);
			boolean isInit = false;
			if (bctRes.isSuccess()) {
				List<BaseCodeType> bctList = bctRes.getEntity();
				if (null != bctList && bctList.size() > 0) {
					isInit = true;
				}
			}
			String[] codeTypeArr = { "获知途径", "客户性质", "置业动机", "关注重点", "需求楼层", "生活服务", "生活配套", "希望庭院具备功能", "家庭结构",
					"目前居住的物业类型", "首次接触方式", "证件类型", "车驾品牌", "乐于参加的活动类型", "兴趣爱好", "日常信息获知途径", "目前居住的户型结构", 
					"学历","从事行业","公司性质","联系方式","目前居住/办公的房子属性"};
			String[] codeTypeArr2 = { "informedWay", "customerNature", "theirMotives", "focus", "floor", "lifeService", "lifeSupport", "courtyardFunction", "familyJie",
					"currentlyProperty", "contactWay", "documentType", "frameBrand", "activityType", "hobby", "richangxinxi", "currentlyStructure", 
					"academicQualifications","congshihangye","companyXingzhi","contactInformation","currentlyHouse"};
			String[][] codeValueArrs = {
					{ "报广媒体", "网络", "电台广播", "户外广告", "楼宇广告", "杂志", "直投", "会员", "展厅推荐", "房交会", "朋友介绍", "全员营销", "外部推荐",
							"CALL客", "短信", "派单", "工地现场及围挡", "拓客", "中介" },
					{ "自然到访", "员工", "工抵", "全员营销", "外部推荐", "渠道客户", "老带新", "分销推荐" },
					{ "婚房", "改善", "投资", "自住", "养老", "度假" },
					{ "地理位置", "商业配套", "周边配套", "生态环境", "健康服务", "建筑风水", "户型设计", "教育机构" },
					{ "多层", "小高层", "高层", "1层", "2层", "3层", "4层", "5层", "6层" },
					{ "酒店式礼宾服务", "酒店式前台服务", "酒店式商务服务", "菜单式房屋清洁服务", "私人生活秘书", "送餐服务", "文化、体育活动", "专车接送服务", "房屋租赁管理服务",
							"电话及访客留言", "健康、教育课程服务", "24小时便利店", "银行", "医院", "学校", "地铁", "公交", "菜场", "超市", "健身房", "药店",
							"图书馆" },
					{ "银行", "医院", "学校", "地铁", "公交", "菜场", "超市", "健身房" },
					{ "游泳池", "SPA池", "水景池", "烧烤台", "凉亭" },
					{ "独居", "夫妻二人", "二代同堂", "三代同堂", "四代同堂" },
					{ "酒店式公寓", "高层公寓", "多层公寓", "平层官邸", "排屋", "别墅", "中式大宅" },
					{ "来电", "来访" },
					{ "身份证", "护照", "营业执照", "户口簿", "军官证", "临时身份证", "港澳台同胞来往通行证", "边民出入境通行证", "外国人永久居留证", "警官证", "士兵证" },
					{ "无车", "奔驰", "宝马", "保时捷", "雷克萨斯", "丰田", "本田", "大众", "雪佛兰", "英菲尼迪", "奥迪", "沃尔沃", "标致", "现代", "别克",
							"福特", "马自达" },
					{ "修身养生类", "知识学习类", "少儿教育类", "老年人关爱类", "互动交流类", "园区体验类", "奢侈品体验类" },
					{ "运动", "上网", "收藏", "音乐", "文学", "摄影", "棋牌", "舞蹈", "旅游", "字画", "阅读", "影视剧", "综艺娱乐", "汽车", "奢侈品",
							"科技", "金融理财", "美容", "养生", "茶艺", "宠物", "烹饪" },
					{ "报纸", "网络", "电台广播", "微信等社交软件", "电视", "短信", "DM单页", "朋友" },
					{ "一室一厅", "两室一厅", "三室一厅", "三室两厅", "两室两厅" },
					{ "大专", "本科", "硕士", "博士", "博士后" },
					{ "工业制造", "贸易", "农林牧渔", "采矿业", "建筑业","房地产业","金融业","交通运输仓储和邮政业","IT行业（信息传输、计算机服务和软件业）","酒店/餐饮业","租赁（和商务服务业）","教育","医疗卫生","文化和体育","旅游","公共管理（政府机关等）和社会组织","科学研究和技术服务","国际组织" },
					{ "私企", "央企", "国企", "混合所有制"},
					{ "电话", "短信", "邮件"},
					{ "安置房", "自建房", "租房","单位分房","07年前老商品房","07年后老商品房","近百年来房子"}
					
				};

			if (isInit) {
				ar.setFailMsg("已初始化,请勿重复操作!");
			} else {
				ProjectDto entity = new ProjectDto();
				entity.setId(dto.getProjectId());
				boolean flag = baseCodeValueServiceFacade.baseCodeValueInit(user, entity, codeTypeArr, codeTypeArr2, codeValueArrs,
						CodeTypeEnum.CUSTOMER.getNo());
				if (flag) {
					ar.setSucceedMsg("初始化成功");
				}
			}

		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg("初始化失败");
		}
		// }
		return ar;
	}
	
	// 查询项目列表
	@RequestMapping(value = "projectList")
	@ResponseBody
	public AjaxRes projectList(ProjectDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		// if(ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON,"system:baseCodeValue:init"))){
		try {
			User user = ShiroUtil.getCurrentUser();
			if(user == null){
				ar.setFailMsg("未登录");
				return ar;
			}
			dto.setMerchantId(user.getMerchantId());
			Page<Project> response = projectServiceFacade.findPageByDto(dto, 
					PageUtil.begin(pageNum, pageSize), pageSize);
			if(!response.getSuccess()){
				ar.setFailMsg(Const.DATA_FAIL);
				return ar;
			}
			
			if (null == response.getRows()){
				response.setRows(new ArrayList<Project>());
			}
			//查询各项目下最新修改人
			for(Project pro : response.getRows()){
				BaseCodeValueDto entity = new BaseCodeValueDto();
				entity.setMerchantId(pro.getMerchantId());
				entity.setProjectId(pro.getId());
				Response<BaseCodeValue> resBcv = baseCodeValueServiceFacade.lastUpdateTime(entity);
				if(!resBcv.isSuccess() || resBcv.getEntity() == null){
					pro.setUpdateTime(null);
					pro.setRemark("");
					continue;
				}
				pro.setRemark(""); 
				Response<User> resUser = userServiceFacade.findById(resBcv.getEntity().getUpdateUserId());
				if(resUser.isSuccess() && resUser.getEntity() != null){
					pro.setRemark(resUser.getEntity().getUserName()); //修改人
				}
				pro.setUpdateTime(resBcv.getEntity().getUpdateTime()); //修改时间
			}
			response.setPageNumber(pageNum);
			ar.setSucceed(response);
			
		} catch (Exception e) {
			logger.error(e.toString(), e);
			ar.setFailMsg(Const.DATA_FAIL);
		}
		return ar;
	}
	
	/**
	 * 跳转复制选项页面
	 * @param map
	 * @return
	 */
	@RequestMapping(value = "toCopyBaseCode")
	public String toCopyBaseCode(Long projectId, ModelMap map) {
		User user = ShiroUtil.getCurrentUser();
		
		ProjectDto dto = new ProjectDto();
		dto.setMerchantId(user.getMerchantId());
		ResponseList<Project> response = projectServiceFacade.findByDto(dto);
		if(response.getEntity() == null){
			return Const.NO_AUTHORIZED_URL;
		}
		List<Project> list = response.getEntity();
		//获取当前选中项目的项目名
		String projectName = "";
		for(int i = 0; i < list.size(); i++){
			Project pro = (Project)list.get(i);
			if(pro.getId() == projectId){
				projectName = pro.getProjectName();
				list.remove(i); //去掉使用复制功能的项目
				continue;
			}
		}
		map.addAttribute("projectList", list);
		map.addAttribute("projectId", projectId);
		map.addAttribute("projectName", projectName);
		return "/system/basecode/basecodevalue/copyBaseCode";
	}
	
	/**
	 * 复制选项
	 * @param projectId 申请复制的项目ID
	 * @param copyPid 被复制的项目ID
	 * @return
	 */
	@RequestMapping(value = "copyBaseCode")
	@ResponseBody
	public AjaxRes copyBaseCode(Long projectId, Long copyPid) {
		AjaxRes ar = getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			if (user == null) {
				ar.setFailMsg("未登录");
				return ar;
			}
			Response<String> response = baseCodeTypeServiceFacade.copyBaseCode(
					projectId, copyPid, user);
			if (response == null) {
				ar.setFailMsg("复制其他项目设置的选项失败");
				return ar;
			}
			if (!response.isSuccess()) {
				ar.setFailMsg(response.getResultMessage());
				return ar;
			}
			ar.setRes(Const.SUCCEED);
		} catch (Exception e) {
			logger.error("复制业务参数失败", e);
			ar.setFailMsg("复制其他项目设置的选项失败");
		}
		return ar;
	}
	
	/**
	 * 生成客户问卷
	 * @param projectId 项目ID
	 * @return
	 */
	@RequestMapping(value = "questionnaire")
	public String questionnaire(Long projectId, ModelMap map) {
		map.addAttribute("projectId", projectId);
		Response<Project> response = projectServiceFacade.findById(projectId);
		if(response.isSuccess() && response.getEntity() != null){
			map.addAttribute("projectName", response.getEntity().getProjectName());
		}
		
		//付款方式
		map.addAttribute("paymentMethodEnum", EnumUtil.toList(PaymentMethodEnum.class));
		//购买车位
		map.addAttribute("buyCarEnum", EnumUtil.toList(BuyCarEnum.class));
		//需求户型规格
		map.addAttribute("xuQiuHuXingEnum", EnumUtil.toList(XuQiuHuXingEnum.class));
		//是否本公司业主
		map.addAttribute("isOwnerCompanyEnum", EnumUtil.toList(IsOwnerCompanyEnum.class));
		return "/system/basecode/basecodevalue/questionnaire";
	}
	
	/**
	 * 客户分析
	 * @param projectId 项目ID
	 * @return
	 */
	@RequestMapping(value = "analysed")
	public String analysed(HttpServletRequest request, Long projectId, ModelMap map) {
		map.addAttribute("projectId", projectId);
		Response<Project> response = projectServiceFacade.findById(projectId);
		if(response.isSuccess() && response.getEntity() != null){
			map.addAttribute("projectName", response.getEntity().getProjectName());
		}
		
		//付款方式
		map.addAttribute("paymentMethodEnum", EnumUtil.toList(PaymentMethodEnum.class));
		//购买车位
		map.addAttribute("buyCarEnum", EnumUtil.toList(BuyCarEnum.class));
		//需求户型规格
		map.addAttribute("xuQiuHuXingEnum", EnumUtil.toList(XuQiuHuXingEnum.class));
		//是否本公司业主
		map.addAttribute("isOwnerCompanyEnum", EnumUtil.toList(IsOwnerCompanyEnum.class));
		
		//查询该项目下的总客户数
		User user = ShiroUtil.getCurrentUser();
		CustomerDto dto = new CustomerDto();
		dto.setMerchantId(user.getMerchantId());
		dto.setProjectId(projectId);
		dto.setDelFlag(DelFlagEnum.UNDEL.getNo());
		ResponseList<Customer> reslist = customerServiceFacade.findByDto(dto);
		int num = 0;
		if(reslist.isSuccess() && reslist.getEntity() != null){
			num = reslist.getEntity().size();
		}
		map.addAttribute("num", num);
		//将客户数量放入缓存
		request.getSession().setAttribute("getQuestionnaireNum", num);
		return "/system/basecode/basecodevalue/analysed";
	}
	
	/**
	 * 获取问卷答题率
	 * 答题率=答这题的人数/问卷答题人数
	 * @param projectId 项目ID
	 * @return
	 */
	@RequestMapping(value = "getSubjectRatio")
	@ResponseBody
	public AjaxRes getSubjectRatio(HttpServletRequest request, Long projectId) {
		AjaxRes ar = getAjaxRes();
		try {
			User user = ShiroUtil.getCurrentUser();
			if (user == null) {
				ar.setFailMsg("未登录");
				return ar;
			}
			//获取全部人数
			String num = request.getSession().getAttribute("getQuestionnaireNum").toString();
			if(StringUtils.isBlank(num) || "0".equals(num)){
				ar.setFailMsg("没有客户提交该问卷");
				return ar;
			}
			//获取问卷答题率
			CustomerDto dto = new CustomerDto();
			dto.setMerchantId(user.getMerchantId());
			dto.setProjectId(projectId);
			List<String[]> list = customerServiceFacade.getSubjectRatio(dto, num);
			if(list != null){
				ar.setSucceed(list);
				//将答题数写入缓存
				setCache(list, user.getMerchantId().toString(), projectId.toString());
			}
			ar.setRes(Const.SUCCEED);
		}catch(Exception ex){
			logger.error("获取问卷答题率失败", ex);
			ar.setFailMsg("获取问卷答题率失败");
		}
		return ar;
	}
	/**
	 * 获取问卷答题选项比例（BaseCodeValue）
	 * 选项比例=选项人数/答这题的人数
	 * @param request
	 * @param projectId 项目ID
	 * @param typeValue 查询的业务参数类型
	 * @param codeName 对应的数据库字段
	 * @return
	 */
	@RequestMapping(value = "getOptionRatio")
	@ResponseBody
	public List<BaseCodeValueInfo> getOptionRatio(String projectId, String typeValue, String codeName) {
		List<BaseCodeValueInfo> bctList = new ArrayList<BaseCodeValueInfo>();
		if(StringUtils.isBlank(projectId)){
			return bctList;
		}
		//获取当前用户
		User user = ShiroUtil.getCurrentUser();
		//获取答题数
		String num = getCache(codeName, user.getMerchantId().toString(), projectId.toString());
		
		//查询选项及比例
		BaseCodeValueInfo bcvDto = new BaseCodeValueInfo();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setTypeName(typeValue);
		bcvDto.setField(codeName);
		bcvDto.setProjectId(Long.parseLong(projectId));
		ResponseList<BaseCodeValueInfo> resList = 
				baseCodeValueServiceFacade.getOptionRatio(bcvDto, num);
		if (null != resList && resList.getEntity() != null 
				&& resList.getEntity().size() > 0) {
			bctList = resList.getEntity();
		}
		
		//查询结束后，清除缓存
		delCache(codeName, user.getMerchantId().toString(), projectId.toString());
		return bctList;
	}
	
	/**
	 * 获取问卷答题选项比例（BaseCodeValue）
	 * 选项比例=选项人数/答这题的人数
	 * @param request
	 * @param projectId 项目ID
	 * @param codeName 对应的数据库字段
	 * @return
	 */
	@RequestMapping(value = "getOptionRatioByEnum")
	@ResponseBody
	public List<BaseCodeValueInfo> getOptionRatioByEnum(String projectId, String codeName) {
		List<BaseCodeValueInfo> bctList = new ArrayList<BaseCodeValueInfo>();
		//判断项目ID是否为空
		if(StringUtils.isBlank(projectId)){
			return bctList;
		}
		//获取当前用户
		User user = ShiroUtil.getCurrentUser();
		//从缓存中获取答题数
		String num = getCache(codeName, user.getMerchantId().toString(), projectId.toString());
		
		//查询选项及比例
		BaseCodeValueInfo bcvDto = new BaseCodeValueInfo();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setField(codeName);
		bcvDto.setProjectId(Long.parseLong(projectId));
		ResponseList<BaseCodeValueInfo> resList = 
				baseCodeValueServiceFacade.getOptionRatioByEnum(bcvDto, num, codeName);
		if (null != resList && resList.getEntity() != null 
				&& resList.getEntity().size() > 0) {
			bctList = resList.getEntity();
		}
		
		//查询结束后，清除缓存
		delCache(codeName, user.getMerchantId().toString(), projectId.toString());
		return bctList;
	}
	
	/**
	 * 获取家庭成员证件类型的选项比例
	 * 选项比例=选项人数/答这题的人数
	 * @param request
	 * @param projectId 项目ID
	 * @return
	 */
	@RequestMapping(value = "getDocumentTypeRatio")
	@ResponseBody
	public List<BaseCodeValueInfo> getDocumentTypeRatio(HttpServletRequest request, String projectId) {
		List<BaseCodeValueInfo> bctList = new ArrayList<BaseCodeValueInfo>();
		if(StringUtils.isBlank(projectId)){
			return bctList;
		}
		//获取当前用户
		User user = ShiroUtil.getCurrentUser();
		//获取全部人数
		String num = request.getSession().getAttribute("getQuestionnaireNum").toString();
		if(StringUtils.isBlank(num) || "0".equals(num)){
			return bctList;
		}
		
		//查询选项及比例
		BaseCodeValueInfo bcvDto = new BaseCodeValueInfo();
		bcvDto.setMerchantId(user.getMerchantId());
		bcvDto.setProjectId(Long.parseLong(projectId));
		ResponseList<BaseCodeValueInfo> resList = 
				baseCodeValueServiceFacade.getDocumentTypeRatio(bcvDto, num);
		if (null != resList && resList.getEntity() != null 
				&& resList.getEntity().size() > 0) {
			bctList = resList.getEntity();
		}
		
		return bctList;
	}
	
	/**
	 * 将问卷答题数写入缓存
	 */
	private void setCache(List<String[]> list,
			String merchantId, String projectId){
		for(String[] str : list){
			setCache(merchantId, projectId, "customerSex", "customer_sex", str[0], str[2]); //性别
			setCache(merchantId, projectId, "intentionLevel", "intention_level", str[0], str[2]); //意向等级
			setCache(merchantId, projectId, "customerStatus", "customer_status", str[0], str[2]); //客户状态
			setCache(merchantId, projectId, "customerOrigin", "customer_origin", str[0], str[2]); //客户性质
			setCache(merchantId, projectId, "informedWay_t", "informed_way", str[0], str[2]); //获知途径
			setCache(merchantId, projectId, "rqTheirMotives", "rq_their_motives", str[0], str[2]); //置业动机
			setCache(merchantId, projectId, "rqFocusId", "rq_focus_id", str[0], str[2]); //关注重点
			setCache(merchantId, projectId, "rqDemandArea", "rq_demand_area", str[0], str[2]); //需求面积
			setCache(merchantId, projectId, "rqDemandFloor", "rq_demand_floor", str[0], str[2]); //需求楼层
			setCache(merchantId, projectId, "rqServicesId", "rq_services_id", str[0], str[2]); //生活服务
			setCache(merchantId, projectId, "rqLifeSupport", "rq_life_support", str[0], str[2]); //生活配套
			setCache(merchantId, projectId, "rqBudgetSumprice", "rq_budget_sumprice", str[0], str[2]); //预算总价
			setCache(merchantId, projectId, "rqBudgetPrice", "rq_budget_price", str[0], str[2]); //预算单价
			setCache(merchantId, projectId, "rqCourtyardFunction", "rq_courtyard_function", str[0], str[2]); //希望庭院具备功能
			setCache(merchantId, projectId, "rqPaymentMethod", "rq_payment_method", str[0], str[2]); //付款方式
			setCache(merchantId, projectId, "familyJie_t", "family_jie", str[0], str[2]); //家庭结构
			setCache(merchantId, projectId, "buyCar", "buy_car", str[0], str[2]); //购买车位
			setCache(merchantId, projectId, "xuqiuhuxingType", "xuqiuhuxing_type", str[0], str[2]); //需求户型规格
			setCache(merchantId, projectId, "ftContactWay", "ft_contact_way", str[0], str[2]); //接触方式
			setCache(merchantId, projectId, "peDocumentType", "pe_document_type", str[0], str[2]); //证件类型
			setCache(merchantId, projectId, "peDomicilePlace", "pe_domicile_place", str[0], str[2]); //户籍所在地
			setCache(merchantId, projectId, "peFrameBrandId", "pe_frame_brand_id", str[0], str[2]); //车驾品牌
			setCache(merchantId, projectId, "peHouseholdIncome", "pe_household_income", str[0], str[2]); //家庭年收入
			setCache(merchantId, projectId, "peActivityType", "pe_activity_type", str[0], str[2]); //乐于参加的活动类型
			setCache(merchantId, projectId, "peHobbyId", "pe_hobby_id", str[0], str[2]); //兴趣爱好
			setCache(merchantId, projectId, "peAcademicQualifications", "pe_academic_qualifications", str[0], str[2]); //学历
			setCache(merchantId, projectId, "congshihangye_t", "congshihangye", str[0], str[2]); //从事行业
			setCache(merchantId, projectId, "companyXingzhi_t", "company_xingzhi", str[0], str[2]); //公司性质
			setCache(merchantId, projectId, "isYezhu_t", "is_yezhu", str[0], str[2]); //是否本公司业主
			setCache(merchantId, projectId, "richangxinxi_t" , "richangxinxi", str[0], str[2]); //日常信息获取途径
			setCache(merchantId, projectId, "isZinv_t", "is_zinv", str[0], str[2]); //是否有子女
			setCache(merchantId, projectId, "isLaoren_t", "is_laoren", str[0], str[2]); //是否与老人同住
			setCache(merchantId, projectId, "isYuangong_t", "is_yuangong", str[0], str[2]); //是否员工
			setCache(merchantId, projectId, "reCurrentlyProperty", "re_currently_property", str[0], str[2]); //目前居住的物业类型
			setCache(merchantId, projectId, "reCurrentlyArea", "re_currently_area", str[0], str[2]); //目前居住的面积
			setCache(merchantId, projectId, "reCurrentlyHouse", "re_currently_house", str[0], str[2]); //目前居住/办公的房子属性
			setCache(merchantId, projectId, "reCurrentlyStructure", "re_currently_structure", str[0], str[2]); //目前居住的户型结构
			setCache(merchantId, projectId, "coContactTime", "co_contact_time", str[0], str[2]); //工作日联系时间
			setCache(merchantId, projectId, "coInformationDays", "co_information_days", str[0], str[2]); //工作日联系方式
			setCache(merchantId, projectId, "coContactWeekend", "co_contact_weekend", str[0], str[2]); //周末联系时间
			setCache(merchantId, projectId, "coWeekendInformation", "co_weekend_information", str[0], str[2]); //周末联系方式
		}
	}
	private void setCache(String merchantId, String projectId, 
			String codeName, String newName, String name, String num){
		if(codeName.equals(name)){
			cacheUtils.put(EhcacheConstant.ACTIVE_SESSIONS_CACHE, merchantId+"_"+projectId+"_"+newName, num);
		}
	}
	/**
	 * 获取缓存
	 */
	private String getCache(String codeName, 
			String merchantId, String projectId){
		String str = null;
		Object cache = cacheUtils.get(EhcacheConstant.ACTIVE_SESSIONS_CACHE, merchantId+"_"+projectId+"_"+codeName);
		if(cache != null){
			str = cache.toString();
		}
		return str;
	}
	/**
	 * 清除缓存
	 */
	private void delCache(String codeName, 
			String merchantId, String projectId){
		cacheUtils.remove(EhcacheConstant.ACTIVE_SESSIONS_CACHE, merchantId+"_"+projectId+"_"+codeName);
	}

}
